﻿using System;
using System.Windows.Forms;

namespace Editor
{
    partial class EditorWindow
    {
        private void OnDocumentChanged()
        {
            if (!String.IsNullOrEmpty(m_Document.SceneName))
                this.Text = m_Document.SceneName + " - " + Application.ProductName;
            else
                this.Text = "[Untitled] - " + Application.ProductName;

            m_EditType = EditType.Select;
            UpdateEditTypeButtons();
            UpdateUndoRedoStates();

            RegisterViews(this.Controls);
            m_Document.CommandManager.CommandExecuted += new Command.CommandExecutedEventHandler(UpdateUndoRedoStates);
        }

        private void CreateNewDocument()
        {
            m_Document = new EditorDocument(null);

            OnDocumentChanged();
        }

        private void LoadDocument(String sceneFileName)
        {
            m_Document = new EditorDocument(sceneFileName);

            OnDocumentChanged();
        }

        private void SaveDocument(String sceneFileName)
        {
            if (String.IsNullOrEmpty(sceneFileName))
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.AddExtension = true;
                sfd.CheckFileExists = false;
                sfd.CheckPathExists = true;
                sfd.DefaultExt = "scn";
                sfd.DereferenceLinks = true;
                sfd.FileName = (!String.IsNullOrEmpty(Properties.Settings.Default.LastOpenDocument)) ? System.IO.Path.GetFileName(Properties.Settings.Default.LastOpenDocument) : null;
                sfd.Filter = "Scene Files (*.scn)|*.scn|All Files (*.*)|*.*";
                sfd.FilterIndex = 0;
                sfd.InitialDirectory = (!String.IsNullOrEmpty(Properties.Settings.Default.LastOpenDocument)) ? System.IO.Path.GetDirectoryName(Properties.Settings.Default.LastOpenDocument) : Application.StartupPath;
                sfd.OverwritePrompt = true;
                sfd.RestoreDirectory = true;
                sfd.SupportMultiDottedExtensions = true;
                sfd.Title = "Save Scene As";
                sfd.ValidateNames = true;

                if (sfd.ShowDialog(this) == DialogResult.Cancel)
                    return;

                Properties.Settings.Default.LastOpenDocument = sfd.FileName;
                Properties.Settings.Default.Save();

                sceneFileName = sfd.FileName;
            }

            // Save
			bool bSaved = m_Document.Save(sceneFileName);
			if (!bSaved)
			{
				MessageBox.Show(this, "WARNING: The scene has not been saved.\nFile: " + sceneFileName + "\n\nPlease make sure that it is open for edit in Perforce and writable.", "Scene Not Saved", MessageBoxButtons.OK);
			}

            //
            OnDocumentChanged();
        }
    }
}
